package com.lagou.zuoye.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DbUtil {
    private static String jdbcName;    //用于描述驱动信息
    private static String dbUrl;    //用于描述URL信息
    private static String dbUserName;   //用于描述用户名信息
    private static String dbPassword;   //用于描述用户密码信息

    //进行静态成员的初始化操作
    static {
        jdbcName = "com.mysql.jdbc.Driver";
        dbUrl = "jdbc:mysql://localhost:3306/db_web?characterEncoding=UTF-8";
        dbUserName = "root";
        dbPassword = "laopan8023xx";

        try {
            Class.forName(jdbcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
        return connection;
    }

    /**
     * 关闭连接
     * @param connection
     * @throws SQLException
     */
    public static void closeResource(Connection connection, PreparedStatement ps) throws SQLException {
        if(null!=connection){
            connection.close();
        }

        if(null!=ps){
            ps.close();
        }
    }

    public static void closeResource(Connection connection) throws SQLException {
        if(null!=connection){
            connection.close();
        }
    }
}
